package com.mex_native.rfid;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.mex_native.MainActivity;
import com.rscja.deviceapi.RFIDWithUHF;

public class RFIDModule extends ReactContextBaseJavaModule implements RFIDInterface {

    private static ReactApplicationContext reactContext;

    private Callback readTagCallback = null;
    private Callback readTagFailCallback = null;

    boolean isReInit = false;

    boolean loopFlag = true;
    // public Reader mReader;
    // public Reader mReader;
    public static RFIDWithUHF mReader = null;

    public RFIDModule(ReactApplicationContext context) {
        super(context);
        reactContext = context;
        MainActivity.getInstances().rfidInterface = this;


    }

    /**
     * 发送消息RFID值到RN
     * @param
     */
    public static void didGetRFID(String rfid) {
        sendEventToRn("didGetRFID", rfid);
    }
    public static void sendEventToRn(String eventName, Object msg) {
        if (reactContext == null) {
            return;
        }
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName,msg);
    }


    @NonNull
    @Override
    public String getName() {
        return "RFIDModule";
    }


    //RN调用的方法,给暴露给JS的方法添加 @ReactMethod 注解，且方法的返回值只能是void
    /*
     * checkType : 判断类型
     * successCallback : 成功的回调
     * errCallback : 失败的回调
     * */
    @ReactMethod
    public void startScanRFID(Callback successCallback, Callback errCallback){
        initUHF();
        this.readTagCallback = successCallback;
        this.readTagFailCallback = errCallback;
    }

    //RN调用的方法,给暴露给JS的方法添加 @ReactMethod 注解，且方法的返回值只能是void
    /*
     * checkType : 判断类型
     * successCallback : 成功的回调
     * errCallback : 失败的回调
     * */
    @ReactMethod
    public void stopScanRFID(Callback successCallback, Callback errCallback){
        this.readTagCallback = null;
        closeUHF();
    }

    public void  closeUHF(){
        if (mReader != null){
            mReader.free();
        }
    }


    public void initUHF() {

        try {
//            if (mReader != null){
//                return;
//            }

            mReader = RFIDWithUHF.getInstance();

        } catch (Exception ex) {

            toastMessage(ex.getMessage());

            return;
        }

        if (mReader != null) {
            new InitTask().execute();
        }
    }


    public void toastMessage(String msg) {
        Toast.makeText(getCurrentActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void readTag() {
        if (mReader == null){
            toastMessage("mReader is null");
            return;
        }
        switch (0) {
            case 0:// 单步
            {

                mReader.setEPCTIDMode(true);
                loopFlag = true;
                if (mReader.startInventoryTag(0,0)) {

                    new TagThread().start();
                } else {
//                        mReader.stopInventory();
//					mContext.playSound(2);
                }



//                        Message msg = handler.obtainMessage();
//                        msg.obj = strResult + "EPC:" + mContext.mReader.convertUiiToEPC(res[1]) + "@" + res[2];
            }
            break;
            case 1:// 单标签循环  .startInventoryTag((byte) 0, (byte) 0))
            {

            }
            break;
            default:
                break;
        }
    }

    public class InitTask extends AsyncTask<String, Integer, Boolean> {
        ProgressDialog mypDialog;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            return mReader.init();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            mypDialog.cancel();

            if (!result) {
                Toast.makeText(getCurrentActivity(), "init fail",
                        Toast.LENGTH_SHORT).show();

                //重新试一次
                if (mReader != null && !isReInit){
                    mReader.free();
                    initUHF();

                    isReInit = true;
                }


            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            mypDialog = new ProgressDialog(getCurrentActivity());
            mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mypDialog.setMessage("init...");
            mypDialog.setCanceledOnTouchOutside(false);
            mypDialog.show();
        }
    }






    class TagThread extends Thread {
        public void run() {

            String strTid;
            String strResult;
            String[] res = null;

            while (loopFlag) {
                res = mReader.readTagFromBuffer();
                if (res != null) {
                    strTid = res[0];
                    if (strTid.length() != 0 && !strTid.equals("0000000" +
                            "000000000") && !strTid.equals("000000000000000000000000")) {
                        strResult = "TID:" + strTid + "\n";
                    } else {
                        strResult = "";
                    }
                    Log.i("data","EPC:"+res[1]+"|"+strResult);

                    loopFlag = false;


                    String finalTid = strTid;
                    String finalEpc = mReader.convertUiiToEPC(res[1]);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {

                            didGetRFID(finalTid);
                            if (finalTid != null && finalEpc != null ){
                                if (readTagCallback != null){
                                    readTagCallback.invoke(finalTid);
                                    readTagCallback = null;
                                }
                            }else{
                                if(readTagFailCallback != null){
                                    readTagFailCallback.invoke("调用失败！");
                                    readTagFailCallback = null;
                                }
                            }
                        }
                    });
                }
            }
        }

    }




}
